package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean checkExists(String data, Integer type) {

        if (StringUtils.isEmpty(data) || (2 == type && !RegexUtils.isPhone(data))) {
            throw new LyException(400, "请求参数有误");
        }

        String colName = null;
        switch (type) {
            case 1:
                colName = "username";
                break;
            case 2:
                colName = "phone";
                break;
            default:
                throw new LyException(400, "请求参数有误");
        }

        return query().eq(colName, data).count() == 1;
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX = "user:verify:code:";

    @Override
    public void sendVerifyCode(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误");
        }

        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);

        String code = RandomStringUtils.randomNumeric(6);
        msg.put("code", code);

        this.amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);

        this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void userRegister(User user, String code) {

        String key = KEY_PREFIX + user.getPhone();

        if (StringUtils.isEmpty(code) || !redisTemplate.hasKey(key) || !code.equals(redisTemplate.opsForValue().get(key))) {
            throw new LyException(400, "验证码输入有误");
        }

        String encodePassword = this.passwordEncoder.encode(user.getPassword());

        user.setPassword(encodePassword);


        save(user);

        //this.passwordEncoder.matches("heima110",user.getPassword());
    }

    @Override
    public UserDTO queryUserByNameAndPass(String username, String password) {

        User user = query().eq("username", username).one();

        if (null==user|| !passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"用户名或密码错误");
        }

        return new UserDTO(user);
    }
}
